﻿using System;
using System.Web.Security;

namespace ECommerce.Administration.MasterPage
{
	public partial class ECommerceAdmin : System.Web.UI.MasterPage
	{
		private Service.ILanguageService _LanguageService;
		//private Service.ILocalStringResourceService _LocalStringResourceService;

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!Roles.IsUserInRole("Administrator"))
			{
				Server.Transfer("~/Administration/AdminLogin.aspx");
			}

			if(!IsPostBack)
			{
				BindLanguages();
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			if (SiteContext.Current != null)
			{
				var lang = SiteContext.Current.WorkingLanguage;

				if (lang != null)
				{ 
					DropDownlistLanguages.SelectedIndex = DropDownlistLanguages.Items.IndexOf(DropDownlistLanguages.Items.FindByValue(lang.LanguageId.ToString()));
				}
			}
		}

		private void BindLanguages()
		{
			if (_LanguageService == null)
			{
				_LanguageService = new Service.LanguageService();
			}

			var languages = _LanguageService.GetAllLanguage();

			DropDownlistLanguages.DataSource = languages;
			DropDownlistLanguages.DataBind();
		}

		protected void DropDownlistLanguages_SelectedIndexChanged(object sender, EventArgs e)
		{
			var selectedValue = DropDownlistLanguages.SelectedValue;

			int selectedLanguageID = 0;

			if (int.TryParse(selectedValue, out selectedLanguageID))
			{
				AdminLocalLizationManager.ChangeCurrentCulture(selectedLanguageID);
			}
		}

		//public System.Collections.Generic.IEnumerable<Data.Entity.LocalStringResource> LocaleStringResources
		//{
		//    get
		//    {
		//        if (SiteContext.Current == null)
		//        {
		//            Server.Transfer("~Administration/AdminLogin.aspx");
		//        }

		//        var currentLanguage = SiteContext.Current.WorkingLanguage;

		//        if (currentLanguage != null)
		//        {
		//            if (_LocalStringResourceService == null)
		//            {
		//                _LocalStringResourceService = new Service.LocalStringResourceService();
		//            }

		//            return _LocalStringResourceService.GetLocaleStringResourceByLanguage(currentLanguage.LanguageId);
		//        }
		//        else
		//        {
		//            return null;
		//        }
		//    }
		//}

		//public string GetLocalResourceString(string name)
		//{
		//    if(string.IsNullOrEmpty(name))
		//    {
		//        return string.Empty;
		//    }

		//    return (from v in LocaleStringResources
		//            where v.ResourceName == name
		//            select v.ResourceValue).FirstOrDefault();

		//}
	}
}
